package com.rabbitmq.ChattingRoom.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.json.JSONUtil;
import com.rabbitmq.ChattingRoom.util.common.base.Result;
import com.rabbitmq.ChattingRoom.util.config.GiteePagesConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping(value = "file")
@Transactional(rollbackFor = Exception.class)
public class FileController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 上传图片
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadfile")
    @ResponseBody
    public Result<Object> uploadImg(@RequestParam("file") MultipartFile file) throws Exception {
        String originaFileName = file.getOriginalFilename();
        //上传图片不存在时
        if(originaFileName == null){
            return Result.error("上传图片不存在!");
        }

        String suffix = originaFileName.substring(originaFileName.lastIndexOf("."));
        //设置图片名字
        String fileName = System.currentTimeMillis() + "_" + UUID.randomUUID().toString() + suffix;

        String paramImgFile = Base64.encode(file.getBytes());

        //设置转存到Gitee仓库参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("access_token", GiteePagesConfig.ACCESS_TOKEN);
        paramMap.put("message", GiteePagesConfig.ADD_MESSAGE);
        paramMap.put("content", paramImgFile);

        //转存文件路径
        String targetDir = "/" + fileName;
        //设置请求路径
        String requestUrl = GiteePagesConfig.CREATE_REPOS_URL + targetDir;
        logger.info("请求Gitee仓库路径:{}",requestUrl);

        String resultJson = HttpUtil.post(requestUrl, paramMap);
        JSONObject jsonObject = JSONUtil.parseObj(resultJson);
        //表示操作失败
        if (jsonObject==null || jsonObject.getObj("commit") == null) {
            return Result.error("服务器内部异常!");
        }
        JSONObject content = JSONUtil.parseObj(jsonObject.getObj("content"));

        return Result.success("上传成功!",content.getObj("download_url"));
    }

}
